#P1.3.1: 导入模块并定义常量
import socket
MSG_LENGTH = 64
DISCONNECTED = '!CONNECTION CLOSED'

#P1.3.2: 定义远程服务器地址
remote_ip = socket.gethostbyname(socket.gethostname())
remote_port = 5050
remote_addr = (remote_ip, remote_port)

#P1.3.3: 创建客户机套接字并连接远程服务器
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(remote_addr)
print(f'客户机工作地址：{client_socket.getsockname()}')

#P1.3.4: 向服务器发送消息并接收回送消息的函数
def send_recv(msg):
    """
    功能：客户机向服务器发送消息并接收服务器的回送消息
    :param msg: 消息内容
    """
    message = msg.encode('utf-8')
    msg_len = len(message)
    str_len = str(msg_len).encode('utf-8')
    str_len += b' ' * (MSG_LENGTH - len(str_len))
    client_socket.send(str_len)
    client_socket.send(message)
    echo_message = client_socket.recv(1024).decode('utf-8')
    print(echo_message)

#P1.3.5: 会话循环
while True:
    inputStr = input('请输入待发送的字符串（Q：结束会话）：')
    if inputStr.lower() == 'q':
        break
    send_recv(inputStr)

#P1.3.6: 发送断开连接消息并关闭套接字
send_recv(DISCONNECTED)
client_socket.close()    